package com.duapk.search.util;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 布隆过滤器池
 * 
 * @Package: com.duapk.search.util
 * @ClassName: BloomFilterPool
 * @author: jiangzheng
 * @date: Jun 7, 2011 3:25:10 PM
 * 
 */
public class BloomFilterPool {

	private static final int KEY_NUMS = 2000000;

	private static final int CORE_POOL_SIZE = 200;

	private static final int MAX_POOL_SIZE = 500;

	private static final int NUM_HASH_FUNCTIONS = 8;

	private static final byte[] LOCK = new byte[0];

	private int poolSize;

	private ArrayBlockingQueue<BloomFilter> pool = new ArrayBlockingQueue<BloomFilter>(
			MAX_POOL_SIZE);

	private static BloomFilterPool instance = null;

	private BloomFilterPool() {
		poolSize = CORE_POOL_SIZE;
		for (int i = 0; i < CORE_POOL_SIZE; i++) {
			BloomFilter bl = new BloomFilter(KEY_NUMS, NUM_HASH_FUNCTIONS);
			pool.add(bl);
		}
	}

	public static BloomFilterPool getInstance() {
		if (instance == null) {
			synchronized (LOCK) {
				if (instance == null) {
					instance = new BloomFilterPool();
				}
			}
		}
		return instance;
	}

	public BloomFilter getBloomFilter() {
		BloomFilter bl = pool.poll();
		if (bl == null && poolSize < MAX_POOL_SIZE) {
			bl = new BloomFilter(KEY_NUMS, NUM_HASH_FUNCTIONS);
			synchronized (LOCK) {
				if (poolSize < MAX_POOL_SIZE) {
					pool.add(bl);
					poolSize++;
				}
			}
		}
		return bl;
	}

	public void release(BloomFilter bl) {
		bl.reset();
		pool.add(bl);
	}
}
